<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数字记录统计工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <!-- 引入SheetJS库用于导出Excel -->
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .date-picker {
                overflow-x: auto;
                scrollbar-width: none;
                -webkit-overflow-scrolling: touch;
                scroll-snap-type: x mandatory;
            }
            .date-item {
                scroll-snap-align: center;
                min-width: 80px;
            }
            .date-item-selected {
                background-color: #e8f0fe;
                border-color: #4285f4;
            }
            .file-item {
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4285f4',
                        secondary: '#e8f0fe',
                        neutral: '#f5f5f5',
                        dark: '#333333',
                    },
                    fontFamily: {
                        sans: ['Microsoft YaHei', 'sans-serif'],
                    },
                }
            }
        }
    </script>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- 顶部日期选择器 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 transition-all duration-300 hover:shadow-xl">
            <div class="flex flex-col md:flex-row items-center justify-between gap-4">
                <div class="text-xl font-bold text-dark mb-4 md:mb-0">
                    <i class="fa fa-calendar-check-o text-primary mr-2"></i>数字记录统计
                </div>
                <div class="text-sm text-gray-500">
                    <span id="currentDateTime"></span>
                </div>
            </div>
            
            <!-- 滑动日期选择器 -->
            <div class="mt-4 relative">
                <div class="absolute left-0 top-0 bottom-0 w-12 bg-gradient-to-r from-white to-transparent pointer-events-none z-10"></div>
                <div class="absolute right-0 top-0 bottom-0 w-12 bg-gradient-to-l from-white to-transparent pointer-events-none z-10"></div>
                
                <div id="datePicker" class="date-picker flex py-2 scrollbar-hide">
                    <!-- 日期项将通过JS动态生成 -->
                </div>
                
                <div class="absolute left-1/2 top-0 bottom-0 w-px bg-primary/30 transform -translate-x-1/2 pointer-events-none"></div>
            </div>
            
            <!-- 数字输入区 -->
            <div class="mt-6 flex items-center">
                <span class="text-gray-700 mr-2">次数:</span>
                <input type="number" id="valueInput" placeholder="输入数字" min="0" 
                       class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all">
                <button id="saveBtn" class="ml-4 px-6 py-2 bg-primary text-white rounded-lg shadow hover:bg-primary/90 transition-all flex items-center">
                    <i class="fa fa-save mr-2"></i>保存记录
                </button>
            </div>
        </div>
        
        <!-- 日历视图 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 transition-all duration-300 hover:shadow-xl">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-semibold text-dark">
                    <i class="fa fa-calendar text-primary mr-2"></i>历史记录日历
                </h2>
                <div class="flex space-x-2">
                    <button id="prevMonthBtn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                        <i class="fa fa-chevron-left text-primary"></i>
                    </button>
                    <span id="currentCalendarMonth" class="text-sm font-medium">2025年5月</span>
                    <button id="nextMonthBtn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                        <i class="fa fa-chevron-right text-primary"></i>
                    </button>
                </div>
            </div>
            
            <!-- 日历网格 -->
            <div class="grid grid-cols-7 gap-1">
                <!-- 星期标题 -->
                <div class="text-center text-sm font-medium text-gray-500 py-2">日</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">一</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">二</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">三</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">四</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">五</div>
                <div class="text-center text-sm font-medium text-gray-500 py-2">六</div>
                
                <!-- 日历内容将通过JS动态生成 -->
                <div id="calendarGrid" class="col-span-7 grid grid-cols-7 gap-1">
                    <!-- 日历内容 -->
                </div>
            </div>
        </div>
        
        <!-- 统计图表 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 transition-all duration-300 hover:shadow-xl">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4">
                <h2 class="text-lg font-semibold text-dark mb-2 md:mb-0">
                    <i class="fa fa-line-chart text-primary mr-2"></i>次数统计图表
                </h2>
                <div class="flex space-x-2">
                    <button class="chart-period-btn px-3 py-1 text-xs rounded-full bg-primary text-white" data-period="15">15天</button>
                    <button class="chart-period-btn px-3 py-1 text-xs rounded-full bg-gray-100 text-gray-600" data-period="30">1个月</button>
                    <button class="chart-period-btn px-3 py-1 text-xs rounded-full bg-gray-100 text-gray-600" data-period="90">3个月</button>
                    <button class="chart-period-btn px-3 py-1 text-xs rounded-full bg-gray-100 text-gray-600" data-period="180">半年</button>
                </div>
            </div>
            
            <!-- 图表容器 -->
            <div class="h-64 md:h-80">
                <canvas id="statsChart"></canvas>
            </div>
            
            <!-- 统计总数和导出按钮 -->
            <div class="mt-4 flex flex-col sm:flex-row justify-between items-center">
                <div class="mb-2 sm:mb-0">
                    <span class="text-sm text-gray-500">所选时间段内的总次数:</span>
                    <span id="totalCount" class="text-xl font-bold text-primary ml-2">0</span>
                </div>
                <button id="exportBtn" class="px-4 py-1.5 text-sm bg-primary text-white rounded-lg shadow hover:bg-primary/90 transition-all flex items-center">
                    <i class="fa fa-download mr-1"></i>导出Excel
                </button>
            </div>
        </div>
        
        <!-- 导出的文件列表 -->
        <div id="exportedFiles" class="bg-white rounded-xl shadow-lg p-6 transition-all duration-300 hover:shadow-xl">
            <h2 class="text-lg font-semibold text-dark mb-4">
                <i class="fa fa-file-excel-o text-green-500 mr-2"></i>导出的文件
            </h2>
            <div id="fileList" class="space-y-3">
                <!-- 导出的文件将在这里显示 -->
                <div class="text-gray-500 text-sm italic">暂无导出文件</div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentDate = new Date();
        let selectedDate = new Date(); // 用户当前选择的日期
        let currentCalendarMonth = currentDate.getMonth();
        let currentCalendarYear = currentDate.getFullYear();
        let records = {}; // 存储格式: { "2025-05-15": 5 }
        let statsChart = null;
        let selectedPeriod = 15; // 默认显示15天数据
        let exportedFiles = []; // 存储已导出的文件
        
        // DOM元素
        const datePicker = document.getElementById('datePicker');
        const currentDateTimeEl = document.getElementById('currentDateTime');
        const valueInput = document.getElementById('valueInput');
        const saveBtn = document.getElementById('saveBtn');
        const prevMonthBtn = document.getElementById('prevMonthBtn');
        const nextMonthBtn = document.getElementById('nextMonthBtn');
        const currentCalendarMonthEl = document.getElementById('currentCalendarMonth');
        const calendarGrid = document.getElementById('calendarGrid');
        const chartPeriodBtns = document.querySelectorAll('.chart-period-btn');
        const totalCountEl = document.getElementById('totalCount');
        const exportBtn = document.getElementById('exportBtn');
        const fileList = document.getElementById('fileList');
        
        // 从本地存储加载历史记录和导出文件记录
        function loadRecords() {
            const savedRecords = localStorage.getItem('numberRecords');
            if (savedRecords) {
                records = JSON.parse(savedRecords);
            }
            
            const savedFiles = localStorage.getItem('exportedFiles');
            if (savedFiles) {
                exportedFiles = JSON.parse(savedFiles);
                renderFileList();
            }
        }
        
        // 保存记录到本地存储
        function saveRecords() {
            localStorage.setItem('numberRecords', JSON.stringify(records));
        }
        
        // 保存导出文件记录
        function saveExportedFiles() {
            localStorage.setItem('exportedFiles', JSON.stringify(exportedFiles));
        }
        
        // 更新当前日期时间显示
        function updateCurrentDateTime() {
            const now = new Date();
            const options = { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit', 
                hour: '2-digit', 
                minute: '2-digit', 
                second: '2-digit',
                hour12: false
            };
            currentDateTimeEl.textContent = now.toLocaleString('zh-CN', options);
        }
        
        // 初始化日期选择器
        function initDatePicker() {
            // 清空日期选择器
            datePicker.innerHTML = '';
            
            // 生成前30天、当前日期和后30天
            for (let i = -30; i <= 30; i++) {
                const date = new Date();
                date.setDate(currentDate.getDate() + i);
                
                const isToday = date.toDateString() === currentDate.toDateString();
                const isSelected = date.toDateString() === selectedDate.toDateString();
                
                const dateItem = createDateItem(date, isToday, isSelected);
                datePicker.appendChild(dateItem);
            }
            
            // 滚动到当前选择的日期
            setTimeout(() => {
                const selectedItem = datePicker.querySelector('.date-item-selected');
                if (selectedItem) {
                    selectedItem.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
                }
            }, 100);
        }
        
        // 创建日期项
        function createDateItem(date, isToday, isSelected) {
            const dateStr = date.toDateString();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
            
            // 检查是否有记录
            const recordDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const hasRecord = records[recordDate] !== undefined;
            
            const dateItem = document.createElement('div');
            dateItem.className = `date-item flex flex-col items-center justify-center p-2 rounded-lg border-2 cursor-pointer transition-all ${
                isSelected ? 'date-item-selected font-bold' : 'border-gray-100 hover:border-primary/30'
            }`;
            dateItem.dataset.date = dateStr;
            
            // 点击事件
            dateItem.addEventListener('click', () => {
                // 移除之前的选中状态
                document.querySelectorAll('.date-item').forEach(item => {
                    item.classList.remove('date-item-selected', 'font-bold');
                    item.classList.add('border-gray-100', 'hover:border-primary/30');
                });
                
                // 添加新的选中状态
                dateItem.classList.remove('border-gray-100', 'hover:border-primary/30');
                dateItem.classList.add('date-item-selected', 'font-bold');
                
                // 更新选中的日期
                selectedDate = new Date(date);
                
                // 如果有记录，填充到输入框
                if (hasRecord) {
                    valueInput.value = records[recordDate];
                } else {
                    valueInput.value = '';
                }
            });
            
            // 日期内容
            let dateContent = `
                <div class="text-xs text-gray-500">${month}/${day}</div>
                <div class="text-sm">周${weekDay}</div>
            `;
            
            // 如果有记录，添加记录显示
            if (hasRecord) {
                dateContent += `<div class="text-xs text-primary font-bold">${records[recordDate]}</div>`;
            }
            
            // 如果是今天，添加标记
            if (isToday) {
                dateContent += '<div class="w-1 h-1 bg-primary rounded-full mt-1"></div>';
            }
            
            dateItem.innerHTML = dateContent;
            
            return dateItem;
        }
        
        // 保存当前选择的数值记录
        function saveValue() {
            const value = parseInt(valueInput.value);
            
            if (isNaN(value) || value < 0) {
                showToast('请输入有效的正整数', 'error');
                return;
            }
            
            const year = selectedDate.getFullYear();
            const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
            const day = String(selectedDate.getDate()).padStart(2, '0');
            const dateKey = `${year}-${month}-${day}`;
            
            records[dateKey] = value;
            saveRecords();
            
            // 更新UI
            initDatePicker();
            renderCalendar();
            updateChart();
            
            showToast(`已记录 ${dateKey} 的次数: ${value}`, 'success');
        }
        
        // 导出数据为Excel
        function exportToExcel() {
            // 获取当前图表显示的数据
            const today = new Date();
            const data = [];
            
            // 修改：使用正向序列作为序号
            for (let i = 0; i < selectedPeriod; i++) {
                const date = new Date(today);
                date.setDate(today.getDate() - (selectedPeriod - 1 - i)); // 调整日期计算方式
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const dateStr = `${year}-${month}-${day}`;
                
                // 添加数据行，序号从1开始递增
                data.push({
                    序号: i + 1,
                    日期: dateStr,
                    次数: records[dateStr] || 0
                });
            }
            
            // 创建工作簿和工作表
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.json_to_sheet(data);
            
            // 设置表头样式
            const range = XLSX.utils.decode_range(ws['!ref']);
            for (let c = range.s.c; c <= range.e.c; c++) {
                const cell = XLSX.utils.encode_cell({r: 0, c: c});
                if (!ws[cell]) continue;
                ws[cell].s = { font: { bold: true }, fill: { fgColor: { rgb: "D3D3D3" } } };
            }
            
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "统计数据");
            
            // 生成Excel文件
            const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            
            // 创建Blob对象
            const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
            
            // 生成文件名（统计起始日期至结束日期）
            const startDate = new Date(today);
            startDate.setDate(today.getDate() - selectedPeriod + 1);
            const endDate = today;
            
            const startDateStr = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')}`;
            const endDateStr = `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')}`;
            
            const fileName = `次数统计_${startDateStr}_至_${endDateStr}.xlsx`;
            
            // 创建文件URL
            const fileUrl = URL.createObjectURL(blob);
            
            // 保存文件信息
            const fileInfo = {
                id: Date.now(),
                name: fileName,
                url: fileUrl,
                date: new Date().toISOString(),
                blob: blob // 保存blob以便后续使用
            };
            
            exportedFiles.unshift(fileInfo);
            saveExportedFiles();
            renderFileList();
            
            showToast(`数据已导出为Excel文件`, 'success');
        }
        
        // 渲染文件列表
        function renderFileList() {
            // 清空文件列表
            fileList.innerHTML = '';
            
            if (exportedFiles.length === 0) {
                fileList.innerHTML = '<div class="text-gray-500 text-sm italic">暂无导出文件</div>';
                return;
            }
            
            // 渲染文件列表
            exportedFiles.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item flex items-center justify-between p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-all';
                
                // 文件信息
                const fileInfo = document.createElement('div');
                fileInfo.className = 'flex items-center';
                
                // 文件图标
                const fileIcon = document.createElement('div');
                fileIcon.className = 'w-8 h-8 flex items-center justify-center bg-green-100 text-green-600 rounded mr-3';
                fileIcon.innerHTML = '<i class="fa fa-file-excel-o"></i>';
                fileInfo.appendChild(fileIcon);
                
                // 文件名称和日期
                const fileDetails = document.createElement('div');
                fileDetails.className = 'flex flex-col';
                
                const fileName = document.createElement('div');
                fileName.className = 'text-sm font-medium text-gray-800 truncate max-w-xs';
                fileName.textContent = file.name;
                fileDetails.appendChild(fileName);
                
                const fileDate = document.createElement('div');
                fileDate.className = 'text-xs text-gray-500';
                const date = new Date(file.date);
                fileDate.textContent = date.toLocaleString('zh-CN');
                fileDetails.appendChild(fileDate);
                
                fileInfo.appendChild(fileDetails);
                fileItem.appendChild(fileInfo);
                
                // 文件操作按钮
                const fileActions = document.createElement('div');
                fileActions.className = 'flex space-x-2';
                
                // 打开按钮
                const openBtn = document.createElement('button');
                openBtn.className = 'p-1.5 text-gray-600 hover:text-primary rounded-full hover:bg-primary/10 transition-colors';
                openBtn.innerHTML = '<i class="fa fa-eye"></i>';
                openBtn.addEventListener('click', () => {
                    // 在新窗口中打开文件
                    window.open(file.url, '_blank');
                });
                fileActions.appendChild(openBtn);
                
                // 下载按钮
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'p-1.5 text-gray-600 hover:text-primary rounded-full hover:bg-primary/10 transition-colors';
                downloadBtn.innerHTML = '<i class="fa fa-download"></i>';
                downloadBtn.addEventListener('click', () => {
                    // 创建下载链接
                    const a = document.createElement('a');
                    a.href = file.url;
                    a.download = file.name;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
                fileActions.appendChild(downloadBtn);
                
                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'p-1.5 text-gray-600 hover:text-red-500 rounded-full hover:bg-red-100 transition-colors';
                deleteBtn.innerHTML = '<i class="fa fa-trash"></i>';
                deleteBtn.addEventListener('click', () => {
                    // 从列表中移除文件
                    const index = exportedFiles.findIndex(f => f.id === file.id);
                    if (index !== -1) {
                        // 释放URL对象
                        URL.revokeObjectURL(exportedFiles[index].url);
                        exportedFiles.splice(index, 1);
                        saveExportedFiles();
                        renderFileList();
                        showToast('文件已删除', 'info');
                    }
                });
                fileActions.appendChild(deleteBtn);
                
                fileItem.appendChild(fileActions);
                fileList.appendChild(fileItem);
            });
        }
        
        // 显示提示消息
        function showToast(message, type = 'success') {
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `fixed bottom-4 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 ${
                type === 'success' ? 'bg-green-500 text-white' : 
                type === 'error' ? 'bg-red-500 text-white' : 'bg-gray-500 text-white'
            }`;
            toast.textContent = message;
            
            // 添加到页面
            document.body.appendChild(toast);
            
            // 3秒后移除
            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-y-4');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }
        
        // 渲染日历
        function renderCalendar() {
            // 清空日历网格
            calendarGrid.innerHTML = '';
            
            // 设置当前月份标题
            currentCalendarMonthEl.textContent = 
                `${currentCalendarYear}年${currentCalendarMonth + 1}月`;
            
            // 获取当月第一天是星期几 (0-6, 0是星期日)
            const firstDay = new Date(currentCalendarYear, currentCalendarMonth, 1).getDay();
            
            // 获取当月的天数
            const daysInMonth = new Date(currentCalendarYear, currentCalendarMonth + 1, 0).getDate();
            
            // 获取今天的日期
            const today = new Date();
            const isCurrentMonth = today.getFullYear() === currentCalendarYear && 
                                  today.getMonth() === currentCalendarMonth;
            const todayDate = today.getDate();
            
            // 添加上个月的占位空格
            for (let i = 0; i < firstDay; i++) {
                const emptyCell = document.createElement('div');
                emptyCell.className = 'aspect-square bg-gray-50 rounded p-1 flex flex-col';
                calendarGrid.appendChild(emptyCell);
            }
            
            // 添加当月的日期
            for (let day = 1; day <= daysInMonth; day++) {
                const cell = document.createElement('div');
                cell.className = 'aspect-square bg-white rounded p-1 flex flex-col border border-gray-100 hover:border-primary/30 hover:bg-gray-50 transition-all';
                
                // 如果是今天，添加特殊样式
                if (isCurrentMonth && day === todayDate) {
                    cell.classList.add('bg-secondary');
                }
                
                // 创建日期元素
                const dateElement = document.createElement('div');
                dateElement.className = 'text-xs font-medium text-gray-500';
                dateElement.textContent = day;
                cell.appendChild(dateElement);
                
                // 检查是否有记录
                const monthStr = String(currentCalendarMonth + 1).padStart(2, '0');
                const dayStr = String(day).padStart(2, '0');
                const dateKey = `${currentCalendarYear}-${monthStr}-${dayStr}`;
                
                if (records[dateKey]) {
                    const valueElement = document.createElement('div');
                    valueElement.className = 'mt-auto text-center text-lg font-bold text-primary';
                    valueElement.textContent = records[dateKey];
                    cell.appendChild(valueElement);
                }
                
                calendarGrid.appendChild(cell);
            }
        }
        
        // 初始化统计图表
        function initChart() {
            const ctx = document.getElementById('statsChart').getContext('2d');
            
            // 销毁已存在的图表
            if (statsChart) {
                statsChart.destroy();
            }
            
            // 创建新图表
            statsChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '次数',
                        data: [],
                        borderColor: '#4285f4',
                        backgroundColor: 'rgba(66, 133, 244, 0.1)',
                        borderWidth: 2,
                        pointBackgroundColor: '#4285f4',
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        tension: 0.2,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    return `次数: ${context.raw}`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            min: 0,
                            max: 3,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    },
                    animation: {
                        duration: 500
                    }
                }
            });
        }
        
        // 更新统计图表
        function updateChart() {
            if (!statsChart) {
                initChart();
            }
            
            // 获取最近n天的数据
            const today = new Date();
            const daysData = [];
            
            for (let i = selectedPeriod - 1; i >= 0; i--) {
                const date = new Date(today);
                date.setDate(today.getDate() - i);
                const dateStr = date.toISOString().split('T')[0];
                
                // 添加日期标签
                const label = `${date.getMonth() + 1}/${date.getDate()}`;
                
                // 添加数据值
                const value = records[dateStr] || 0;
                
                daysData.push({
                    dateStr,
                    label,
                    value
                });
            }
            
            // 更新图表数据
            statsChart.data.labels = daysData.map(item => item.label);
            statsChart.data.datasets[0].data = daysData.map(item => item.value);
            statsChart.update();
            
            // 更新总数
            const total = daysData.reduce((sum, item) => sum + item.value, 0);
            totalCountEl.textContent = total;
        }
        
        // 初始化事件监听
        function initEventListeners() {
            // 保存按钮点击事件
            saveBtn.addEventListener('click', saveValue);
            
            // 回车键保存
            valueInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    saveValue();
                }
            });
            
            // 上月/下月按钮事件
            prevMonthBtn.addEventListener('click', () => {
                currentCalendarMonth--;
                if (currentCalendarMonth < 0) {
                    currentCalendarMonth = 11;
                    currentCalendarYear--;
                }
                renderCalendar();
            });
            
            nextMonthBtn.addEventListener('click', () => {
                currentCalendarMonth++;
                if (currentCalendarMonth > 11) {
                    currentCalendarMonth = 0;
                    currentCalendarYear++;
                }
                renderCalendar();
            });
            
            // 图表周期选择按钮事件
            chartPeriodBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    // 移除所有按钮的激活状态
                    chartPeriodBtns.forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-100', 'text-gray-600');
                    });
                    
                    // 添加当前按钮的激活状态
                    btn.classList.remove('bg-gray-100', 'text-gray-600');
                    btn.classList.add('bg-primary', 'text-white');
                    
                    // 更新所选周期
                    selectedPeriod = parseInt(btn.dataset.period);
                    
                    // 更新图表
                    updateChart();
                });
            });
            
            // 为日期选择器添加滚动事件监听
            datePicker.addEventListener('scroll', () => {
                // 获取可视区域中间位置
                const centerX = datePicker.scrollLeft + datePicker.clientWidth / 2;
                
                // 查找最接近中间位置的日期项
                let closestItem = null;
                let minDistance = Infinity;
                
                datePicker.querySelectorAll('.date-item').forEach(item => {
                    const itemRect = item.getBoundingClientRect();
                    const itemCenterX = itemRect.left + itemRect.width / 2;
                    const distance = Math.abs(itemCenterX - centerX);
                    
                    if (distance < minDistance) {
                        minDistance = distance;
                        closestItem = item;
                    }
                });
                
                // 如果找到最接近的项且不在选中状态，则更新选中状态
                if (closestItem && !closestItem.classList.contains('date-item-selected')) {
                    // 移除之前的选中状态
                    document.querySelectorAll('.date-item').forEach(item => {
                        item.classList.remove('date-item-selected', 'font-bold');
                        item.classList.add('border-gray-100', 'hover:border-primary/30');
                    });
                    
                    // 添加新的选中状态
                    closestItem.classList.remove('border-gray-100', 'hover:border-primary/30');
                    closestItem.classList.add('date-item-selected', 'font-bold');
                    
                    // 更新选中的日期
                    const dateStr = closestItem.dataset.date;
                    selectedDate = new Date(dateStr);
                    
                    // 如果有记录，填充到输入框
                    const year = selectedDate.getFullYear();
                    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
                    const day = String(selectedDate.getDate()).padStart(2, '0');
                    const dateKey = `${year}-${month}-${day}`;
                    
                    if (records[dateKey]) {
                        valueInput.value = records[dateKey];
                    } else {
                        valueInput.value = '';
                    }
                }
            });
            
            // 导出Excel按钮事件
            exportBtn.addEventListener('click', exportToExcel);
        }
        
        // 初始化
        function init() {
            loadRecords();
            initDatePicker();
            renderCalendar();
            initChart();
            updateChart();
            initEventListeners();
            
            // 每秒更新当前时间
            setInterval(updateCurrentDateTime, 1000);
            updateCurrentDateTime();
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>